//
//  SPGeneralPreferences.m
//  Sophie
//
//  Created by Anton Chebotaev on 7/10/09.
//  Copyright 2009 IFMO. All rights reserved.
//

#import "SPGeneralPreferencesViewController.h"

@interface SPGeneralPreferencesViewController (Private) 
- (void)updateAccountView;
@end

@interface SPGeneralPreferencesViewController (Callbacks) 
- (void)accountWillReloadCallback;
- (void)accountDidReloadCallback;
@end

@implementation SPGeneralPreferencesViewController

#pragma mark Lifecycle
- (id)init {
	self = [super initWithNibName:@"GeneralPreferencesTab" bundle:nil];
	
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(accountWillReloadCallback)
												 name:LJAccountWillUpdateNotification
											   object:nil];	
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(accountDidReloadCallback)
												 name:LJAccountDidUpdateNotification
											   object:nil];	
	return self;
}

- (void)dealloc {
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[super dealloc];
}

#pragma mark Required by MBPreferencesModule
- (NSString *)title {
	return NSLocalizedString(@"General", @"Title of 'General' preference pane");
}
- (NSString *)identifier {
	return @"General Preferences";
}
- (NSImage *)image {
	return [NSImage imageNamed:@"NSPreferencesGeneral"];
}

#pragma mark Optional by MBPreferencesModule
- (void)willBeDisplayed {
	[self updateAccountView];
	
	SPPreferencesController *prefController = [SPPreferencesController sharedController];
	[shouldCreateEntryButton setState:[prefController shouldCreateDocumentOnStart]];
	[shouldDetecMusicButton setState:[prefController shouldDetectMusicForNewEntry]];
	[shouldAutosaveButton setState:[prefController shouldUseAutosave]];
	[autosaveIntervalPopUp setEnabled:[prefController shouldUseAutosave]];
	NSDictionary *imagesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
									  [NSImage imageNamed:@"blankicon"] , @"blank",
									  [NSImage imageNamed:@"private"] , @"private",
									  [NSImage imageNamed:@"protected"] , @"friends",
									  [NSImage imageNamed:@"groupsicon"] , @"custom", nil];
	[defaultSecurityLevelPopup setMenu:[LJAccount defaultSecurityMenuWithImages:imagesDictionary]];
	switch ([prefController defaultPrivacyLevel]) {
		case LJPublicEntry:
			[defaultSecurityLevelPopup selectItemAtIndex:0];
			break;
		case LJFriendsOnlyEntry:
			[defaultSecurityLevelPopup selectItemAtIndex:1];
			break;
		case LJPrivateEntry:
			[defaultSecurityLevelPopup selectItemAtIndex:2];
			break;
	}
	switch ([prefController defaultAutosaveInterval]) {
		case 1:
			[autosaveIntervalPopUp selectItemAtIndex:0];
			break;
		case 15:
			[autosaveIntervalPopUp selectItemAtIndex:1];
			break;
		case 30:
			[autosaveIntervalPopUp selectItemAtIndex:2];
			break;
		case 60:
			[autosaveIntervalPopUp selectItemAtIndex:3];
			break;
	}		
}

- (void)updateAccountView {
	LJAccount *account = [[SPAccountController sharedController] sharedAccount];
	
	if (account) {
		[usernameField setStringValue:[account username]];
		[passwordField setStringValue:@"password"];
		LJUserpic *userpic = [account defaultUserpic];
		if ([userpic image]) {
			[defaultUserpicImageView setImage:[[account defaultUserpic] image]];			
		}
	} else {
		[usernameField setStringValue:@""];
		[passwordField setStringValue:@""];
		[defaultUserpicImageView setImage:[NSImage imageNamed:@"userinfo"]];			
	}
}

#pragma mark IBActions
- (IBAction)applyAccountChanges:(id)sender {
	// Add password to keychain
	EMInternetKeychainItem *ki = [[EMKeychainProxy sharedProxy] internetKeychainItemForServer:@"livejournal.com"
																				 withUsername:[usernameField stringValue]
																						 path:@""
																						 port:80
																					 protocol:kSecProtocolTypeHTTP];
	if (ki) {
		[ki setPassword:[passwordField stringValue]];
	} else {
		[[EMKeychainProxy sharedProxy] addInternetKeychainItemForServer:@"livejournal.com"
														   withUsername:[usernameField stringValue]
															   password:[passwordField stringValue]
																   path:@""
																   port:80
															   protocol:kSecProtocolTypeHTTP];	
	}
	
	// Tell account controller to reload
	[[SPAccountController sharedController] reloadFromServerWithUsername:[usernameField stringValue]];
}

- (IBAction)applyPreferences:(id)sender {
	SPPreferencesController *prefController = [SPPreferencesController sharedController];

	[prefController setShouldCreateDocumentOnStart:(BOOL)[shouldCreateEntryButton state]];	
	[prefController setShouldDetectMusicForNewEntry:(BOOL)[shouldDetecMusicButton state]];
	[prefController setDefaultPrivacyLevel:[[[defaultSecurityLevelPopup selectedItem] representedObject] intValue]];
	BOOL shouldAutosave = (BOOL)[shouldAutosaveButton state];
	[autosaveIntervalPopUp setEnabled:shouldAutosave]; 
	[prefController setShouldUseAutosave:shouldAutosave];
	switch ([autosaveIntervalPopUp indexOfSelectedItem]) {
		case 0:
			[prefController setDefaultAutosaveInterval:1];
			break;
		case 1:
			[prefController setDefaultAutosaveInterval:15];
			break;
		case 2:
			[prefController setDefaultAutosaveInterval:30];
			break;
		case 3:
			[prefController setDefaultAutosaveInterval:60];
			break;
	}	
}

#pragma mark Callbacks
- (void)accountWillReloadCallback {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	[defaultUserpicImageView setImage:nil];
	[logginingInIndicator setHidden:NO];
	[logginingInIndicator startAnimation:self];
	
	[pool drain];	
}
- (void)accountDidReloadCallback {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	[self updateAccountView];
	[logginingInIndicator stopAnimation:self];
	[logginingInIndicator setHidden:YES];
	
	[pool drain];	
}
@end
